<template>
  <d2-container type="card">
    <div style="margin: 5px; height: 550px;">
      <SplitPane :min-percent='20' :default-percent='40' split="vertical">
        <template slot="paneL">
          <el-card class="box-card">
            <div class="ai-chat-container">
              <div class="chat-history" ref="chatHistory">
                <div class="welcome-message" v-if="messages.length === 0">
                  <div class="welcome-icon">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM16.5 13.5C16.5 15.16 15.16 16.5 13.5 16.5H10.5C8.84 16.5 7.5 15.16 7.5 13.5V10.5C7.5 8.84 8.84 7.5 10.5 7.5H13.5C15.16 7.5 16.5 8.84 16.5 10.5V13.5Z"
                        fill="#4299e1" />
                      <path d="M13.5 10.5H10.5V13.5H13.5V10.5Z" fill="white" />
                    </svg>
                  </div>
                  <p>欢迎使用AI问答助手，请输入您的问题</p>
                  <p class="small-text">可选择AI智能查询或普通输入查询模式</p>
                </div>

                <!-- 消息记录 -->
                <div v-for="(message, index) in messages" :key="index"
                  :class="['message-item', message.isUser ? 'user-message' : 'ai-message']">
                  <!-- 用户消息 -->
                  <div v-if="message.isUser" class="message-bubble user-bubble">
                    <div class="message-content">{{ message.content }}</div>
                    <div class="message-meta">
                      <span>我</span>
                      <span>{{ message.timestamp }}</span>
                      <span class="query-type" :class="message.queryType === 'ai' ? 'ai-type' : 'normal-type'">
                        {{ message.queryType === 'ai' ? 'AI查询' : '普通查询' }}
                      </span>
                    </div>
                  </div>

                  <!-- AI消息 -->
                  <div v-else class="message-bubble ai-bubble">
                    <div class="ai-icon">
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path
                          d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM16.5 13.5C16.5 15.16 15.16 16.5 13.5 16.5H10.5C8.84 16.5 7.5 15.16 7.5 13.5V10.5C7.5 8.84 8.84 7.5 10.5 7.5H13.5C15.16 7.5 16.5 8.84 16.5 10.5V13.5Z"
                          fill="currentColor" />
                        <path d="M13.5 10.5H10.5V13.5H13.5V10.5Z" fill="white" />
                      </svg>
                    </div>
                    <div class="message-content">{{ message.content }}</div>
                    <div class="message-meta">
                      <span>AI助手</span>
                      <span>{{ message.timestamp }}</span>
                    </div>
                  </div>
                </div>

                <!-- 加载状态 -->
                <div class="loading-indicator" v-if="isLoading">
                  <div class="loading-dots">
                    <span class="dot"></span>
                    <span class="dot"></span>
                    <span class="dot"></span>
                  </div>
                  <p>正在{{ queryType === 'ai' ? 'AI智能分析' : '处理' }}您的请求...</p>
                </div>
              </div>

              <!-- 输入区域 -->
              <div class="input-container">
                <!-- 查询类型选择 -->
                <div class="query-type-selector">
                  <label class="radio-label">
                    <input type="radio" value="ai" v-model="queryType" class="custom-radio">
                    <span class="radio-text ai-radio">AI智能查询</span>
                  </label>
                  <label class="radio-label">
                    <input type="radio" value="normal" v-model="queryType" class="custom-radio">
                    <span class="radio-text normal-radio">普通输入查询</span>
                  </label>
                  <el-button type="primary" @click="showModifyDialog = true">修改 AI 信息</el-button>
                  <el-dialog title="修改信息" :visible.sync="showModifyDialog" width="400px">
                    <div style="display:flex; flex-direction:column; gap:16px;">
                      <div style="display:flex; align-items:center; gap:8px;">
                        <el-checkbox style="width:110px; text-align:center;" v-model="modifyAgentIdChecked">修改AgentID</el-checkbox>
                        <el-input v-model="modifyAgentId" placeholder="AgentID" :disabled="!modifyAgentIdChecked" style="width:220px;" />
                      </div>
                      <div style="display:flex; align-items:center; gap:8px;">
                        <el-checkbox style="width:110px; text-align:center;" v-model="modifyApiKeyChecked">修改API-Key</el-checkbox>
                        <el-input v-model="modifyApiKey" placeholder="API-Key" :disabled="!modifyApiKeyChecked" style="width:220px;" />
                      </div>
                      <div style="display:flex; align-items:center; gap:8px;">
                        <span style="width:110px; text-align:center; display:inline-block;">影响用户</span>
                        <el-input v-model="user" placeholder="用户" style="width:220px;" />
                      </div>
                    </div>
                    <span slot="footer" class="dialog-footer">
                      <el-button @click="showModifyDialog = false">取消</el-button>
                      <el-button type="primary" @click="handleModifyConfirm">确认</el-button>
                    </span>
                  </el-dialog>
                </div>
              </div>

              <div class="input-container">
                <!-- 输入框 -->
                <textarea v-model="userInput" class="message-input" placeholder="请输入您的问题..."
                  @keydown.enter="handleSendMessage($event)" :rows="2"></textarea>

                <!-- 发送按钮 -->
                <button class="send-button" @click="handleSendMessage" :disabled="!userInput.trim() || isLoading">
                  <svg t="1757592614498" class="icon" viewBox="0 0 1024 1024" version="1.1"
                    xmlns="http://www.w3.org/2000/svg" p-id="5751" width="32" height="32">
                    <path
                      d="M915.515273 142.819385 98.213046 458.199122c-46.058539 17.772838-44.90475 43.601756 2.348455 57.622994l197.477685 58.594874 80.292024 238.91085c10.51184 31.277988 37.972822 37.873693 61.462483 14.603752l103.584447-102.611545 204.475018 149.840224c26.565749 19.467242 53.878547 9.222132 61.049613-23.090076l149.210699-672.34491C965.264096 147.505054 946.218922 130.971848 915.515273 142.819385zM791.141174 294.834331l-348.61988 310.610267c-6.268679 5.58499-11.941557 16.652774-12.812263 24.846818l-15.390659 144.697741c-1.728128 16.24808-7.330491 16.918483-12.497501 1.344894l-67.457277-203.338603c-2.638691-7.954906 0.975968-17.705389 8.022355-21.931178l442.114555-265.181253C812.67481 268.984974 815.674251 272.975713 791.141174 294.834331z"
                      p-id="5752" fill="#1296db"></path>
                  </svg>
                </button>
              </div>
            </div>
          </el-card>
        </template>
        <template slot="paneR">
          <SplitPane :min-percent='20' :default-percent='65' split="horizontal">
            <template slot="paneL">
              <el-card class="box-card">
                <div class="gallery-container">
                  <div class="image-grid">
                    <div v-for="(item, index) in currentPageItems" :key="index" class="image-card">
                      <router-link :to="getItemLink(item)" class="image-link">
                        <img :src="getImageUrl(item)" :alt="item.name" class="item-image" @error="handleImageError">
                      </router-link>
                      <div class="item-details">
                        <div class="detail-column name-column">
                          <span class="detail-label">名称:</span>
                          <span class="detail-value">{{ item.name }}</span>
                        </div>
                        <div class="detail-column count-column">
                          <span class="detail-label">数量:</span>
                          <span class="detail-value">{{ item.count }}</span>
                        </div>
                      </div>
                    </div>
                    <div v-for="n in emptyItemsCount" :key="'empty-' + n" class="image-card empty-card"></div>
                  </div>
                </div>
              </el-card>
            </template>
            <template slot="paneR">
              <el-card class="box-card"
                style="display: flex; height: 95%; align-items: center; justify-content: center;">
                <p>内容推荐表单</p>
                <div class="simple-table-container">
                  <el-table :data="tableData" border :show-header="false" size="mini"
                    style="width: 100%; height: 100%; font-size:12px;" height="100%">
                    <el-table-column
                      prop="col1"
                      align="center"
                      width="120"
                      label="名称"
                      v-slot="scope"
                    >
                      <router-link
                        :to="`/webui/main2?context=${scope.row.col1}&user=${user}`"
                        style="color: #409EFF; text-decoration: underline; cursor: pointer;"
                      >
                        {{ scope.row.col1 }}
                      </router-link>
                    </el-table-column>
                    <el-table-column
                      prop="col2"
                      align="center"
                      width="120"
                      label="名称"
                      v-slot="scope"
                    >
                      <router-link
                        :to="`/webui/main2?context=${scope.row.col2}&user=${user}`"
                        style="color: #409EFF; text-decoration: underline; cursor: pointer;"
                      >
                        {{ scope.row.col2 }}
                      </router-link>
                    </el-table-column>
                    <el-table-column
                      prop="col3"
                      align="center"
                      width="120"
                      label="名称"
                      v-slot="scope"
                    >
                      <router-link
                        :to="`/webui/main2?context=${scope.row.col3}&user=${user}`"
                        style="color: #409EFF; text-decoration: underline; cursor: pointer;"
                      >
                        {{ scope.row.col3 }}
                      </router-link>
                    </el-table-column>
                    <el-table-column
                      prop="col4"
                      align="center"
                      width="120"
                      label="名称"
                      v-slot="scope"
                    >
                      <router-link
                        :to="`/webui/main2?context=${scope.row.col4}&user=${user}`"
                        style="color: #409EFF; text-decoration: underline; cursor: pointer;"
                      >
                        {{ scope.row.col4 }}
                      </router-link>
                    </el-table-column>
                    <el-table-column
                      prop="col5"
                      align="center"
                      width="120"
                      label="名称"
                      v-slot="scope"
                    >
                      <router-link
                        :to="`/webui/main2?context=${scope.row.col5}&user=${user}`"
                        style="color: #409EFF; text-decoration: underline; cursor: pointer;"
                      >
                        {{ scope.row.col5 }}
                      </router-link>
                    </el-table-column>
                  </el-table>
                </div>
              </el-card>
            </template>
          </SplitPane>
        </template>
      </SplitPane>
    </div>
  </d2-container>
</template>

<script>
import Vue from 'vue'
import SplitPane from 'vue-splitpane'
import axios from 'axios';
Vue.component('SplitPane', SplitPane)

export default {
  data() {
    return {
      // 聊天相关
      userInput: '',
      messages: [],
      queryType: 'ai', // 默认AI查询
      isLoading: false,
      chatHistory: null,

      // 图片推荐相关
      allItems: [],
      currentPage: 1,
      totalItems: 0,
      user: 'admin',

      // 其它
      ITEMS_PER_PAGE: 4,

      // 全局管理 searchMode/searchName
      searchMode: 0,
      searchName: '',
      searchAi: '',
      showModifyDialog: false,
      modifyAgentIdChecked: false,
      modifyApiKeyChecked: false,
      modifyAgentId: '',
      modifyApiKey: '',

      // 表格相关
      tableData: [],
      recommandData: [],
      // 一维数组数据（15条，示例内容可自定义）
      dataList: [
        "1", "2", "3", "4", "5",
        "6", "7", "8", "9", "10",
        "11", "12", "13", "14", "15"
      ],
      // 表格列配置（5列）
      columns: [
        { prop: 'col1' },
        { prop: 'col2' },
        { prop: 'col3' },
        { prop: 'col4' },
        { prop: 'col5' }
      ],
    };
  },
  computed: {
    currentPageItems() {
      return this.allItems;
    },
    emptyItemsCount() {
      const remaining = this.ITEMS_PER_PAGE - this.currentPageItems.length;
      return remaining > 0 ? remaining : 0;
    }
  },
  methods: {
    handleModifyConfirm() {
      if (this.modifyAgentIdChecked) {
        this.handleAgentIdChange(this.modifyAgentId);
      }
      if (this.modifyApiKeyChecked) {
        this.handleApiKeyChange(this.modifyApiKey);
      }
      this.handleUserConfirm(this.user);
      this.showModifyDialog = false;
    },
    async updateAgent(app_id, user) {
      try {
        const response = await axios.post(`http://localhost:8080/project/setAgent?app_id=${app_id}&name=${user}`);
        if (response.data.code === 1) {
          this.showOperationMessage(`(Success) AI信息更新成功\n\n用户: ${user}\nAgentID: ${app_id}`);
        } else {
          this.showOperationMessage(`(ResponseCodeError) AI信息更新失败\n\n用户: ${user}\nAgentID: ${app_id}`);
        }
      } catch (error) {
        this.showOperationMessage(`(ExceptionError) AI信息更新失败\n\n用户: ${user}\nAgentID: ${app_id}`);
      }
    },
    async updateApiKey(api_key, user) {
      try {
        const response = await axios.post(`http://localhost:8080/project/setAuthorization?authorization=${api_key}&name=${user}`);
        if (response.data.code === 1) {
          this.showOperationMessage(`(Success) API-Key更新成功\n\n用户: ${user}`);
        } else {
          this.showOperationMessage(`(ResponseCodeError) API-Key更新失败\n\n用户: ${user}`);
        }
      } catch (error) {
        this.showOperationMessage(`(ExceptionError) API-Key更新失败\n\n用户: ${user}`);
      }
    },
    handleAgentIdChange(newAgentId) {
      this.updateAgent(newAgentId, this.user);
    },
    handleApiKeyChange(newApiKey) {
      this.updateApiKey(newApiKey, this.user);
    },
    handleUserConfirm(user) {
      this.showOperationMessage(`(Confirm) 用户更新为 ${user}`);
    },
    handleImageError(e) {
      e.target.src = 'https://picsum.photos/200/200?grayscale';
      e.target.alt = '图片加载失败';
    },
    getImageUrl(item) {
      if (item.img && item.img.trim() !== '' && item.img !== null) {
        const result = item.img.match(/[^/.]+(?=\.[^/.]+$)/)[0];
        const url = `http://localhost:8080/project/image/${result}`;
        return url;
      }
      console.log('[getImageUrl] 使用默认图片', item);
      return `http://localhost:8080/project/image/default.jpg`;
    },
    getItemLink(item) {
      return `/webui/main2?context=${item.name}&user=${this.user}`;
    },
    async fetchData() {
      try {
        const response = await fetch(`http://localhost:8080/project/normalRecommand`);
        const result = await response.json();
        if (result.code === 1) {
          this.allItems = result.msg.rows || [];
          this.totalItems = result.msg.total || 0;
        } else {
          this.allItems = [];
          this.totalItems = 0;
        }
      } catch (error) {
        this.allItems = [];
        this.totalItems = 0;
      }
    },
    async fetchData2() {
      try {
        const response2 = await fetch(`http://localhost:8080/project/normalRecommandExpand`);
        const result2 = await response2.json();
        if (result2.code === 1) {
          this.dataList = result2.msg || [];
          this.formatDataToTable();
        } else {
          this.dataList = ['无', '无', '无', '无', '无',
            '无', '无', '无', '无', '无',
            '无', '无', '无', '无', '无'];
            this.formatDataToTable();
        }
      } catch (error) {
        this.allItems = [];
        this.totalItems = 0;
      }
    },
    async fetchRecommandData(question) {
      try {
        const response = await fetch(`http://localhost:8080/project/recommandProductAI?userName=${this.user}&question=${question}`);
        const result = await response.json();
        if (result.code === 1) {
          this.recommandData = result.msg || [];
        } else {
          this.recommandData = [];
        }
      } catch (error) {
        this.recommandData = [];
      }
    },
    
    async handleSearchAiChange(newVal) {
      if (this.searchMode !== 1 && this.searchAi !== '') {
        console.log('[handleSearchAiChange] searchMode != 1, 重置 searchAi');
        this.searchAi = '';
        return;
      }
      try {
        // 这里需要使用到 POST 方法
        console.log('[handleSearchAiChange] 触发AI搜索:', newVal);
        const response = await axios.post(`http://localhost:8080/project/recommandProductAI?userName=${this.user}&question=${newVal}`);
        const result = response.data;
        if (result.code === 1) {
          console.log('[handleSearchAiChange] AI推荐结果:', result.msg);
          this.allItems = result.msg.page.rows || [];
          this.totalItems = result.msg.page.total || 0;

          this.isLoading = false;
          // 通知用户更新完毕
          this.messages.push({
            content: `AI智能查询完毕，已为您推荐相关内容`,
            isUser: false,
            timestamp: new Date().toLocaleTimeString(),
            queryType: this.queryType
          });
          this.showOperationMessage(`(Success) AI智能查询完毕，已为您推荐相关内容`);
        } else {
          this.allItems = [];
          this.totalItems = 0;

          this.isLoading = false;
          this.messages.push({
            content: `AI智能查询完毕，但未找到相关内容，请尝试更换查询内容`,
            isUser: false,
            timestamp: new Date().toLocaleTimeString(),
            queryType: this.queryType
          });
          this.showOperationMessage(`(NoData) 未找到相关内容，请尝试更换查询内容`);
        }
      } catch (error) {
        this.recommandData = [];
        this.isLoading = false;
        this.messages.push({
            content: `AI智能查询失败，请稍后重试`,
            isUser: false,
            timestamp: new Date().toLocaleTimeString(),
            queryType: this.queryType
          });
        this.showOperationMessage(`(ExceptionError) AI智能查询失败，请稍后重试`);
      }
    },
    // 监听 searchName 变化（仅在 searchMode 为 0 时处理）
    async handleSearchNameChange(newVal) {
      if (this.searchMode !== 0 && this.searchName !== '') {
        console.log('[handleSearchNameChange] searchMode != 0, 重置 searchName');
        this.searchName = '';
        return;
      }
      try {
        // 这里需要使用到 POST 方法
        console.log('[handleSearchNameChange] 触发搜索:', newVal);
        const response = await axios.post(`http://localhost:8080/project/recommandByTags?name=${newVal}`);
        const result = response.data;
        if (result.code === 1) {
          console.log('[handleSearchNameChange] 搜索结果:', result.msg);
          this.allItems = result.msg.rows || [];
          this.totalItems = result.msg.total || 0;
        } else {
          this.allItems = [];
          this.totalItems = 0;
        }
      } catch (error) {
        this.allItems = [];
        this.totalItems = 0;
      }
    },
    async handleSearchNameChange2(newVal) {
      if (this.searchMode !== 0 && this.searchName !== '') {
        this.searchName = '';
        return;
      }
      try {
        const response = await axios.post(`http://localhost:8080/project/recommandProduct?name=${newVal}`);
        const result = response.data;
        if (result.code === 1) {
          this.dataList = result.msg || [];
          if (this.dataList.length < 15) {
            for (let i = 0; i < 15 - this.dataList.length; i++) {
              this.dataList.push(' ');
            }
          }
          this.formatDataToTable();
        } else {
          this.dataList = [' ', ' ', ' ', ' ', ' ',
            ' ', ' ', ' ', ' ', ' ',
            ' ', ' ', ' ', ' ', ' '];
          this.formatDataToTable();
        }
      } catch (error) {
        this.allItems = [];
        this.totalItems = 0;
      }
    },
    showOperationMessage(message, type) {
      this.$notify({
                title: '提示',
                message: message
            })
    },
    // 聊天消息滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        if (this.chatHistory) {
          this.chatHistory.scrollTop = this.chatHistory.scrollHeight;
        }
      });
    },
    // 处理发送消息
    handleSendMessage(event) {
      if (event) event.preventDefault();
      const input = this.userInput.trim();
      if (!input || this.isLoading) return;
      const timestamp = new Date().toLocaleTimeString();
      this.messages.push({
        content: input,
        isUser: true,
        timestamp,
        queryType: this.queryType
      });
      this.userInput = '';
      this.isLoading = true;
      setTimeout(() => {
        let reply = '';
        if (this.queryType === 'ai') {
          reply = `请稍候，正在为您查询相关内容...`;
          this.searchMode = 1;
          this.searchAi = input;
        } else {
          reply = `已收到您的查询："${input}"，我们在数据库中找到了以下相似的内容，请您参考。（可通过直接点击图片的方式快捷跳转）`;
          this.searchMode = 0;
          this.searchName = input;
        }
        this.messages.push({
          content: reply,
          isUser: false,
          timestamp: new Date().toLocaleTimeString()
        });
        this.isLoading = false;
        this.scrollToBottom();

        // 加一个延时继续显示 Loading 状态
        if (this.queryType === 'ai') {
          this.isLoading = true;
        }
      }, 1500);
    },
    // 表格相关
    formatDataToTable() {
      const data = [];
      for (let i = 0; i < this.dataList.length; i += 5) {
        data.push({
          col1: this.dataList[i] || '',
          col2: this.dataList[i + 1] || '',
          col3: this.dataList[i + 2] || '',
          col4: this.dataList[i + 3] || '',
          col5: this.dataList[i + 4] || ''
        });
      }
      this.tableData = data;
    },
    handleUpdateData(newData) {
      this.tableData = newData;
    },
    handleRecommandData(newData) {
      this.recommandData = newData;
    },
  },
  watch: {
    messages() {
      this.scrollToBottom();
    },
    searchName(newVal) {
      this.handleSearchNameChange(newVal);
      this.handleSearchNameChange2(newVal);
    },
    searchAi(newVal) {
      this.handleSearchAiChange(newVal);
    }
  },
  created() {
    this.fetchData();
    this.fetchData2();
  },
};
</script>

<style scoped>
.simple-table-container {
  padding: 0;
  background-color: #f7f8fa;
  border-radius: 6px;
  margin: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
  display: flex;
  flex-direction: column;
}

/* 调整表格单元格样式 */
::v-deep .el-table {
  height: 100% !important;
}

::v-deep .el-table__body-wrapper {
  height: 100% !important;
  min-height: 0 !important;
}

::v-deep .el-table__body td {
  padding: 4px 2px;
  font-size: 12px;
  min-width: 40px;
  max-width: 60px;
}

/* 奇数单元格交替变色 */
::v-deep .el-table__body tr td:nth-child(odd) {
  background-color: #f2f3f5;
}

/* 鼠标悬停效果 */
::v-deep .el-table__body tr:hover td {
  background-color: #f0f2f5;
}

/* 单元格文字样式 */
::v-deep .el-table__body td .cell {
  font-size: 12px;
  color: #334155;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0;
  text-align: center;
}

.gallery-container {
  max-width: 1200px;
  margin: 2rem auto;
  padding: 0 1rem;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.gallery-title {
  color: #333;
  font-size: 1.8rem;
  text-align: center;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 2px solid #f0f0f0;
}

/* 3行4列网格布局 */
.image-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.image-card {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.image-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
}

.empty-card {
  background-color: transparent;
  box-shadow: none;
}

.image-link {
  display: block;
  position: relative;
  overflow: hidden;
}

.item-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.image-link:hover .item-image {
  transform: scale(1.05);
}

/* 详情部分 - 2列布局 */
.item-details {
  display: grid;
  grid-template-rows: 1fr 1fr;
  /* 行数 2 */
  grid-template-columns: 1fr;
  /* 列数 1 */
  padding: 0.8rem;
  gap: 0.5rem;
  background-color: #f9f9f9;
}

.detail-column {
  padding: 0.4rem;
}

.detail-label {
  font-size: 0.8rem;
  color: #666;
  margin-right: 0.3rem;
}

.detail-value {
  font-size: 0.9rem;
  font-weight: 500;
  color: #333;
}

.name-column .detail-value {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 分页控制 */
.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1.5rem;
  margin: 2rem 0;
}

.page-btn {
  padding: 0.6rem 1.2rem;
  border: none;
  border-radius: 4px;
  background-color: #4299e1;
  color: white;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: background-color 0.2s ease;
}

.page-btn:disabled {
  background-color: #cbd5e0;
  cursor: not-allowed;
  opacity: 0.7;
}

.page-btn:not(:disabled):hover {
  background-color: #3182ce;
}

.prev-btn {
  flex-direction: row-reverse;
}

.page-info {
  color: #4a5568;
  font-size: 1rem;
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .image-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .image-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .item-image {
    height: 150px;
  }
}

@media (max-width: 480px) {
  .image-grid {
    grid-template-columns: 1fr;
  }

  .pagination-controls {
    gap: 0.8rem;
  }

  .page-btn {
    padding: 0.5rem 0.8rem;
    font-size: 0.9rem;
  }
}

.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  max-width: 800px;
  margin: 0 auto;
  background-color: #f9fafb;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.chat-header {
  background-color: #4299e1;
  color: white;
  padding: 1.5rem;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chat-header h1 {
  margin: 0 0 0.5rem 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.chat-header p {
  margin: 0;
  opacity: 0.9;
  font-size: 0.9rem;
}

.chat-history {
  flex: 1;
  padding: 0.5rem;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-height: 350px;
}

.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  color: #64748b;
  text-align: center;
  margin: auto;
}

.welcome-icon {
  margin-bottom: 1rem;
  opacity: 0.7;
}

.small-text {
  font-size: 0.85rem;
  margin-top: 0.5rem;
  opacity: 0.8;
}

.message-item {
  display: flex;
  max-width: 80%;
}

.user-message {
  margin-left: auto;
  justify-content: flex-end;
}

.ai-message {
  margin-right: auto;
}

.message-bubble {
  padding: 0.8rem 1rem;
  border-radius: 12px;
  position: relative;
  max-width: 100%;
}

.user-bubble {
  background-color: #4299e1;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-bubble {
  background-color: white;
  color: #334155;
  border: 1px solid #e2e8f0;
  border-bottom-left-radius: 4px;
  display: flex;
  align-items: flex-start;
  gap: 0.5rem;
}

.ai-icon {
  color: #4299e1;
  margin-top: 0.2rem;
  flex-shrink: 0;
}

.message-content {
  white-space: pre-wrap;
  line-height: 1.5;
}

.message-meta {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0.5rem;
  font-size: 0.75rem;
  opacity: 0.8;
}

.user-message .message-meta {
  justify-content: flex-end;
}

.query-type {
  padding: 0.1rem 0.5rem;
  border-radius: 10px;
  font-size: 0.7rem;
}

.ai-type {
  background-color: rgba(255, 255, 255, 0.2);
}

.normal-type {
  background-color: rgba(255, 255, 255, 0.2);
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1rem;
  color: #64748b;
  margin-right: auto;
}

.loading-dots {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #4299e1;
  animation: bounce 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {

  0%,
  80%,
  100% {
    transform: scale(0);
  }

  40% {
    transform: scale(1);
  }
}

.input-container {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem;
  background-color: white;
  border-top: 1px solid #e2e8f0;
}

.ai-logo {
  flex-shrink: 0;
  color: #4299e1;
}

.query-type-selector {
  display: flex;
  gap: 1rem;
  align-items: center;
  font-size: 0.85rem;
  color: #64748b;
  flex-shrink: 0;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  cursor: pointer;
}

.custom-radio {
  appearance: none;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  border: 2px solid #94a3b8;
  position: relative;
  cursor: pointer;
}

.custom-radio:checked {
  border-color: #4299e1;
}

.custom-radio:checked::after {
  content: '';
  position: absolute;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #4299e1;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.radio-text {
  transition: color 0.2s;
}

.custom-radio:checked+.ai-radio {
  color: #4299e1;
  font-weight: 500;
}

.custom-radio:checked+.normal-radio {
  color: #10b981;
  font-weight: 500;
}

.message-input {
  flex: 1;
  padding: 0.75rem 1rem;
  height: auto;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  resize: none;
  font-family: inherit;
  font-size: 0.9rem;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.message-input:focus {
  outline: none;
  border-color: #4299e1;
  box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1);
}

.message-input::placeholder {
  color: #94a3b8;
}

.send-button {
  background-color: #ffffff;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 0.75rem;
  cursor: pointer;
  transition: background-color 0.2s, transform 0.1s;
  flex-shrink: 0;
}

.send-button:hover {
  background-color: rgb(130, 178, 255);
}

.send-button:active {
  transform: scale(0.95);
}

.send-button:disabled {
  background-color: #cbd5e0;
  cursor: not-allowed;
}

/* 响应式调整 */
@media (max-width: 640px) {
  .ai-chat-container {
    height: 100vh;
    max-width: 100%;
  }

  .chat-history {
    padding: 1rem;
  }

  .message-item {
    max-width: 90%;
  }

  .input-container {
    padding: 0.75rem;
    gap: 0.5rem;
  }

  .query-type-selector {
    display: none;
  }

  .message-input {
    padding: 0.6rem;
    font-size: 0.85rem;
  }
}
</style>